<template>
  <router-view />
</template>

<script>

import { onMounted, watch } from "vue"
import { useStore } from 'vuex'
import { Toast } from 'vant'
import { loginOut, userMsg } from './api/home.js'
import router from "./router/index.js"

export default {
  setup() {
    const store = useStore()
    onMounted(() => {
      store.commit('initStore')
      console.log(123)
    })
    let websock = null
    const initLocket = () => {
      const url = process.env.NODE_ENV == 'development' ? '192.168.31.50' : '211.149.139.110';
      websock = new WebSocket('ws://' + url + ':18092/server/' + store.state.id);
      websock.onmessage = socketOnmessage
    }
    // 掉线
    const socketOnmessage = (res) => {
      if (res.data == 0) {
        Toast.fail('异地登陆，当前设备已退出登录！')
        store.commit('resetStore')
        websock.close()
        loginOut()
        router.replace('/')
        setTimeout(() => {
          location.reload();
        }, 1000)
      }
    }
    const getUsermsg = async () => {
      const res = await userMsg()
      if (res.code === 200) {
        store.commit('initUsermsg', res.data)
      } else {
        Toast.fail(res.msg)
        store.commit('resetStore')
        router.push('/')
      }
    }
    watch(() => store.state.token, (a) => {
      if (a) {
        initLocket()
        getUsermsg()
      }
    })
  }
}
</script>

<style>
#app{
  height: 100%;
  font-weight: 400;
  background: #141A28;
  overflow-y: auto;
}
</style>
